package red.yancloud.www.ui.activity

import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_video_list.*
import org.jsoup.Jsoup
import red.yancloud.www.R
import red.yancloud.www.base.BaseRefreshActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.VideoList
import red.yancloud.www.ui.adapter.RecycleViewDivider
import red.yancloud.www.ui.adapter.VideoListRecyclerAdapter
import red.yancloud.www.util.AppUtils
import red.yancloud.www.util.ScreenUtils
import red.yancloud.www.util.ToastUtils
import android.content.Context
import android.net.Uri
import com.alibaba.fastjson.JSONObject
import okhttp3.ResponseBody
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import java.util.regex.Pattern


/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/19 15:40
 * E_Mail：yh131412hys@163.com
 * Describe：延云视听
 * Change：
 * @Version：V1.0
 */
class VideoListActivity : BaseRefreshActivity(), View.OnClickListener {

    private val TAG = "VideoListActivity"

    private var keyword:String=""
    private lateinit var mAdapter:VideoListRecyclerAdapter

    override val layoutId: Int
        get() = R.layout.activity_video_list

    override fun configViews() {
        super.configViews()

        videoListActivity_back_iv.setOnClickListener(this)
        initSearchEditText()
    }

    private fun initSearchEditText() {

//        在清单文件对应的Activity中添加如下属性，防止布局被软键盘顶上去 android:windowSoftInputMode="stateAlwaysVisible|adjustPan"
        videoListActivity_search_et.setOnEditorActionListener(object : TextView.OnEditorActionListener {

            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {

                if (actionId== EditorInfo.IME_ACTION_SEARCH) {

                    AppUtils.closeInoutDecorView(this@VideoListActivity)
                    keyword = videoListActivity_search_et.text.toString().trim()
                    videoListActivity_search_et.text!!.clear()
                    if (TextUtils.isEmpty(keyword)) {

                        ToastUtils.showToast("请输入搜索关键字")
                        return true
                    }

                    page = 1
                    videoListActivity_rV.scrollToPosition(0)
                    getRefreshDataList()
//                    keyword=""
                    return true
                }
                return false
            }
        })
    }

    override fun initRecyclerView() {

        videoListActivity_rV.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        videoListActivity_rV.addItemDecoration(
            RecycleViewDivider(
                this,
                DividerItemDecoration.VERTICAL,
                ScreenUtils.dpToPx(10f).toInt(),
                R.color.color_f5
            )
        )
        mAdapter = VideoListRecyclerAdapter(R.layout.item_video_list)
        videoListActivity_rV.adapter = mAdapter
        mAdapter.onItemClickListener = object : BaseQuickAdapter.OnItemClickListener {
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                val videoBean = mAdapter.data[position] as VideoList.DataBean.VideoBean

                if (!TextUtils.isEmpty(videoBean.content)) {

                    val document = Jsoup.parse(videoBean.content)
                    val videoSource = document.select("video").select("source").attr("src")
                    Log.d(TAG, videoSource+isHttpUrl(Constants.BASE_RED_CLOUD_HOST_URL+videoBean.content))

                    if (!TextUtils.isEmpty(videoSource)/*&&isHttpUrl(Constants.BASE_RED_CLOUD_HOST_URL+videoBean.content)*/) {

                        startActivity(
                            Intent(this@VideoListActivity, VideoInfoActivity::class.java)
                                .putExtra("id", videoBean.id)
                        )
                    }
                }

                val fileAddress = videoBean.fileaddress
                if (!TextUtils.isEmpty(fileAddress)) {
                    if (fileAddress.startsWith("http")) {

                        AppUtils.openBrowser(this@VideoListActivity, fileAddress)
//                    startActivity(Intent().setAction("android.intent.action.VIEW").setData(Uri.parse(videoBean.fileaddress)))
                    }else{

//                        AppUtils.openBrowser(this@VideoListActivity, Constants.BASE_RED_CLOUD_HOST_URL+fileAddress)
                        startActivity(
                            Intent(this@VideoListActivity, VideoInfoActivity::class.java)
                                .putExtra("id", videoBean.id)
                        )
                    }
                }
            }
        }

        mAdapter.onItemChildClickListener= object : BaseQuickAdapter.OnItemChildClickListener {
            override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {


                if (UserInfoShardPreference.instance.isLogin) {

                    val videoBean = mAdapter.data[position] as VideoList.DataBean.VideoBean
                    if (videoBean.favorite != null && videoBean.favorite.id != null) {

                        RedCloudApis.getInstance().myCollectDelete(UserInfoShardPreference.instance.uid,videoBean.favorite.id,object : Observer<ResponseBody> {

                            override fun onComplete() {
                            }

                            override fun onSubscribe(d: Disposable) {
                            }

                            override fun onNext(t: ResponseBody) {

                                val result = String(t.bytes())

                                if (!TextUtils.isEmpty(result)) {

                                    val jsonObject = JSONObject.parseObject(result)

                                    if (jsonObject.getString("code") == Constants.SYSTEM_OK) {

                                        page=1
                                        getRefreshDataList()
                                    }else{

                                        ToastUtils.showToast(jsonObject.getString("msg"))
                                    }
                                }else{

                                    ToastUtils.showToast(getString(R.string.cancel_collect_failure))
                                }
                            }

                            override fun onError(e: Throwable) {
                            }
                        })
                    }else{

                        RedCloudApis.getInstance().addFavorite(UserInfoShardPreference.instance.uid,
                            videoBean.title,
                            videoBean.id,Constants.CollectModel.MEDIA,object : Observer<ResponseBody> {
                                override fun onComplete() {
                                }

                                override fun onSubscribe(d: Disposable) {
                                }

                                override fun onNext(t: ResponseBody) {

                                    val result = String(t.bytes())
                                    if (!TextUtils.isEmpty(result)) {

                                        val parseObject = JSONObject.parseObject(result)
                                        if (parseObject.getString("code") == Constants.SYSTEM_OK) {

                                            ToastUtils.showToast(getString(R.string.collect_success))
                                            page=1
                                            getRefreshDataList()
                                        }else{

                                            ToastUtils.showToast(getString(R.string.collect_failure))
                                        }
                                    }
                                }

                                override fun onError(e: Throwable) {

                                    ToastUtils.showToast(getString(R.string.collect_failure))
                                }
                            })
                    }
                }else{

                    ToastUtils.showToast(R.string.not_login_prompt)
                    startActivity(Intent(mContext,LoginActivity::class.java))
                }
            }
        }
    }

    /**
     * 判断字符串是否为URL
     * @param urls 需要判断的String类型url
     * @return true:是URL；false:不是URL
     */
    private fun isHttpUrl(urls: String): Boolean {
        var isurl: Boolean
        val regex =
            "(((https|http)?://)?([a-z0-9]+[.])|(www.))" + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)"//设置正则表达式

//        regex.trim()
        val pat = Pattern.compile(regex.trim { it <= ' ' })//对比
        val mat = pat.matcher(urls.trim { it <= ' ' })
        isurl = mat.matches()//判断是否匹配
        if (isurl) {
            isurl = true
        }
        return isurl
    }

    override fun getRefreshDataList() {

        loadingDialog.show()

        RedCloudApis.getInstance().getMedia(UserInfoShardPreference.instance.uid,page.toString(), limit, "", keyword,object : Observer<ResponseBody> {
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: ResponseBody) {

                    val result = String(t.bytes())
                    Log.d(TAG,result)
                    val jsonObject = JSONObject.parseObject(result)

                    val videoList = VideoList()

                    val code = jsonObject.getString("code")
                    videoList.code = code
                    val msg = jsonObject.getString("msg")
                    videoList.msg = msg

                    if (code == Constants.SYSTEM_OK) {

                        val dataObject = jsonObject.getJSONObject("data")

                        val dataBean = VideoList.DataBean()

                        val pageObject = dataObject.getJSONObject("page")
                        if (pageObject != null) {

                            val count = pageObject.getString("count")
                            totalPage = pageObject.getIntValue("totalPage")
                            val page = pageObject.getString("page")
                            val limit = pageObject.getString("limit")
                            val firstRow = pageObject.getIntValue("firstRow")

                            dataBean.page = VideoList.DataBean.PageBean(count,totalPage,page,limit,firstRow)
                        }

                        val videoArray = dataObject.getJSONArray("video")

                        if (videoArray != null && videoArray.size>0) {

                            val videoInfoList = ArrayList<VideoList.DataBean.VideoBean>()
                            for (i in 0 until videoArray.size) {

                                val videoObject = videoArray[i] as JSONObject

                                val favoriteBean = VideoList.DataBean.VideoBean.FavoriteBean()

                                try {
                                    val favoriteObject = videoObject.getJSONObject("favorite")
                                    if (favoriteObject != null) {

                                        favoriteBean.id = favoriteObject.getString("id")
                                        favoriteBean.title = favoriteObject.getString("title")
                                        favoriteBean.model = favoriteObject.getString("model")
                                    }
                                }catch (c:ClassCastException){

                                }finally {

                                    videoInfoList.add(VideoList.DataBean.VideoBean(
                                        videoObject.getString("id"),
                                        videoObject.getString("title"),
                                        videoObject.getString("thumbnail"),
                                        videoObject.getString("introduce"),
                                        videoObject.getString("content"),
                                        videoObject.getString("addtime"),
                                        videoObject.getString("fileaddress"),
                                        videoObject.getString("tag"),
                                        videoObject.getString("daoyancon"),
                                        videoObject.getString("chupintime"),
                                        videoObject.getString("company"),
                                        videoObject.getString("yuyan"),
                                        favoriteBean))
                                }
                            }

                            dataBean.video = videoInfoList

                            videoList.data = dataBean
                        }

                        Log.d(TAG,videoList.toString())

                        if (videoList.data != null) {

                            if (videoList.data.page != null && videoList.data.video != null && videoList.data.video.size > 0) {

                                totalPage = videoList.data.page.totalPage
                                errorView.visibility = View.GONE
                                smartRefreshLayout.visibility = View.VISIBLE
                                if (page == 1) {

                                    mAdapter.data.clear()
                                    mAdapter.addData(videoList.data.video)
                                    //处理数据加载后，页面刷新异常问题
                                    videoListActivity_rV.scrollBy(1,0)
                                    videoListActivity_rV.scrollBy(-1,0)
                                    smartRefreshLayout.resetNoMoreData()
                                    smartRefreshLayout.finishRefresh()
                                } else {

                                    mAdapter.addData(videoList.data.video)
                                    smartRefreshLayout.finishLoadMore()
                                }
                            } else {

                                if (page == 1) {

                                    smartRefreshLayout.finishRefresh()

                                    errorView.visibility = View.VISIBLE
                                    smartRefreshLayout.visibility = View.GONE
                                } else {

                                    ToastUtils.showToast(getString(R.string.data_all_load))
                                    smartRefreshLayout.finishLoadMore()
                                }
                            }
                        }

                        /*if (t.data != null) {

                            if (t.data.page != null && t.data.video != null && t.data.video.size > 0) {

                                totalPage = t.data.page.totalPage
                                errorView.visibility = View.GONE
                                smartRefreshLayout.visibility = View.VISIBLE
                                if (page == 1) {

                                    mAdapter.data.clear()
                                    mAdapter.addData(t.data.video)
                                    smartRefreshLayout.resetNoMoreData()
                                    smartRefreshLayout.finishRefresh()
                                } else {

                                    mAdapter.addData(t.data.video)
                                    smartRefreshLayout.finishLoadMore()
                                }
                            } else {

                                if (page == 1) {

                                    smartRefreshLayout.finishRefresh()

                                    errorView.visibility = View.VISIBLE
                                    smartRefreshLayout.visibility = View.GONE
                                } else {

                                    ToastUtils.showToast(getString(R.string.data_all_load))
                                    smartRefreshLayout.finishLoadMore()
                                }
                            }
                        }*/
                    }else{

                        errorView.visibility = View.VISIBLE
                        smartRefreshLayout.visibility = View.GONE
                    }

                    loadingDialog.dismiss()
                }

                override fun onError(e: Throwable) {

                    loadingDialog.dismiss()
                    errorView.visibility = View.VISIBLE
                    smartRefreshLayout.visibility = View.GONE
                }
            })
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.videoListActivity_back_iv -> finish()
            else -> {
            }
        }
    }
}
